package com.book.exception;

import com.book.common.exception.BaseException;
import com.book.common.helper.I18nHelper;
import com.book.common.result.Failed;
import com.book.common.result.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * Description：
 *
 * @Author： leo.xiong
 * @CreateDate： 2019/10/15 17:13
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Value("${spring.servlet.multipart.max-request-size}")
    private String maxRequestSize;

    @Autowired
    private I18nHelper i18nHelper;

    @ExceptionHandler(value = BaseException.class)
    public RestResponse defaultErrorHandler(BaseException e) {
        e.printStackTrace();
        return new Failed("BOOK:COMMON:10029", i18nHelper.get("BOOK:COMMON:10029"));
    }

    @ExceptionHandler(value = RuntimeException.class)
    public RestResponse defaultErrorHandler(RuntimeException e) {
        e.printStackTrace();
        if (e instanceof MaxUploadSizeExceededException) {
            return new Failed("BOOK:COMMON:10030", i18nHelper.get("BOOK:COMMON:10030") + maxRequestSize + " M");
        }
        return new Failed("BOOK:COMMON:10029", i18nHelper.get("BOOK:COMMON:10029"));
    }
}
